Ext.namespace("Sdp.Quotations");

Sdp.Quotations = Ext.extend(Ext.app.Module, {
	id : 'quotations',

	init : function(){
		this.launcher = {
			text: 'Quotations',
			iconCls:'bogus',
			handler : this.createWindow,
			scope: this
		}
	},

	getDataSource : function(company) {
		var ds = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({
				url: 'index.php?m=quotations&a=do_search&suppressHeaders=1',
				method: 'POST'
		    }),
		    baseParams:{
		    	company_id: company != undefined ? company.company_id : 0
		    },

			reader: new Ext.data.JsonReader({
	            root: 'rows',
	            totalProperty: 'totalRows',
	        },
	            Ext.data.Record.create([
		            {name: 'quote_id'},
		            {name: 'quote_name'},
		            {name: 'type_name'},
		            {name: 'status_id'},
		            {name: 'status_name'},
		            {name: 'company_id'},
		            {name: 'company_name'},
		            {name: 'shipping_type_name'}
		        ])
        	),

			sortInfo:{field: 'quote_name', direction: "ASC"},

		});
		ds.load({params: {
        	start: 0,
        	limit: 10,
        }});
		return ds;
	},

	makePaggingBar : function(ds, filters) {
		var pagging = new Ext.PagingToolbar({
			pageSize: 10,
			store: ds,
			displayInfo: true,
			displayMsg: 'Displaying quotations {0} - {1} of {2}',
			emptyMsg: 'No quotations to display',
			plugins: filters
		});

		return pagging;
	},

	buildGridFilter : function() {
		Ext.ux.menu.RangeMenu.prototype.icons = {
          gt: 'ext/img/greater_then.png',
          lt: 'ext/img/less_then.png',
          eq: 'ext/img/equals.png'
		};
		Ext.ux.grid.filter.StringFilter.prototype.icon = 'ext/img/find.png';

		var filters = new Ext.ux.grid.GridFilters({
			filters:[
				{type: 'string',  dataIndex: 'quote_code'},
				{type: 'string', dataIndex: 'quote_name'},
				{type: 'string', dataIndex: 'status_id'}
			],

			paramPrefix: 'quote_',

			cleanParams: function(p){
				var regex = new RegExp("^" + this.paramPrefix);
				for(var key in p)
					if(regex.test(key))
						delete p[key];
			},

			buildQuery: function(filters){
                var p = {};
				for(var i=0, len=filters.length; i<len; i++){
					var f    = filters[i];
					for(var key in f.data)
						p[f.field] = f.data[key];
				}

				return p;
		    }
		});

		return filters;
	},

	buildGrid : function(company, config) {
		var sm = new Ext.grid.RowSelectionModel({singleSelect:true});

		var ds = this.getDataSource(company);

		var filters = this.buildGridFilter();

		var grid = new Ext.grid.GridPanel({
			autoExpandColumn:'quote_name',
			border:false,
			ds: ds,
			cm: new Ext.grid.ColumnModel([
				new Ext.grid.RowNumberer(),
				{header: "Code", sortable: true, dataIndex: 'quote_code'},
				{header: "Name", sortable: true, dataIndex: 'quote_name'},
				{header: "Status", sortable: true, dataIndex: 'status_name'},
				{header: "Type", sortable: true, dataIndex: 'type_name'},
				{header: "Shipping type", sortable: true, dataIndex: 'shipping_type_name'}
			]),
			plugins: filters,
			shadow: false,
			shadowOffset: 0,
			sm: sm,
			loadMask: {msg: 'Loading'},
			tbar: [{
				text:'Add Customer',
				tooltip:'Add a new customer',
				iconCls:'icon-add'
			}, '-', {
				text:'Options',
				tooltip:'Blah blah blah blah',
				iconCls:'icon-option'
			},'-',{
				text:'Delete Customer',
				tooltip:'Remove the selected customer',
				iconCls:'icon-remove'
			}],

			bbar: this.makePaggingBar(ds, filters),

			viewConfig: {
				forceFit:true
			}
		});

		if (config != undefined) {
			Ext.applyIf(grid, config);
		}

		this.buildGridAction(grid);

		return grid;
	},

	buildGridAction : function(grid) {
		// example of getting a reference to another module's launcher object

		grid.on({
			rowdblclick : function(g, rowIndex, e) {
				var record = g.getSelectionModel().getSelected();
        		e.stopEvent();
				var m = this.app.getModule('contacts-view');
				m.createWindow({companyId: record.get('company_id')});
        	},

        	scope: this
		});

		// example of how to open another module on rowselect
//		sm.on('rowselect',function(){
//			tabWinLauncher.handler.call(this.scope || this);
//		}, this);
	},

	createWindow : function(){
		var desktop = this.app.getDesktop();
		var win = desktop.getWindow('quotations-win');
		if(!win){
			var grid = this.buildGrid();
            win = desktop.createWindow({
                id: 'quotations-win',
                title:'Customers grid',
                width:740,
                height:480,
                iconCls: 'quotations',
                shim:false,
                animCollapse:false,
                constrainHeader:true,
				layout: 'fit',
                items: grid
            });
		}
		win.show();
	}
});